import {
  mapState,
  mapActions
} from 'vuex';

export default {
  computed: {
    ...mapState(['user', 'defaultUser', 'authToken', 'refreshToken', 'location', 'width', 'height'])
  },

  data() {
    return {
      isMiniprogram: process.env.isMiniprogram
    };
  },

  created() {
    window.resetStoreData = (funName, data) => {
      this[funName](data);
    };
  },

  methods: {
    setUser(user) {
      this.setUserData(user);
      this.setVuexStoreWinData('setUserData', user);
    },

    setDefaultUser(defaultUser) {
      this.setDefaultUserData(defaultUser);
      this.setVuexStoreWinData('setDefaultUserData', defaultUser);
    },

    setAuthToken(authToken) {
      this.setAuthTokenData(authToken);
      this.setVuexStoreWinData('setAuthTokenData', authToken);
    },

    setRefreshToken(refreshToken) {
      this.setRefreshTokenData(refreshToken);
      this.setVuexStoreWinData('setRefreshTokenData', refreshToken);
    },

    setLocation(location) {
      this.setLocationData(location);
      this.setVuexStoreWinData('setLocationData', location);
    },

    setWidth(width) {
      this.setWidthData(width);
      this.setVuexStoreWinData('setWidthData', width);
    },

    setHeight(height) {
      this.setHeightData(height);
      this.setVuexStoreWinData('setHeightData', height);
    },

    setVuexStoreWinData(funName, data) {
      if (!this.isMiniprogram) {
        return;
      }

      let pages = getCurrentPages();
      if (pages.length === 1) {
        return;
      }

      for (let i = 0; i < pages.length; i++) {
        const page = pages[i];
        let win = page.window;
        if (win === window) {
          continue;
        }

        if (win.resetStoreData) {
          win.resetStoreData(funName, data);
        }
      }
    },

    ...mapActions(['setUserData', 'setDefaultUserData', 'setAuthTokenData', 'setRefreshTokenData', 'setLocationData', 'setWidthData',
      'setHeightData'])
  }
};
